package com.umeox.watch.moto.camera.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.umeox.watch.moto.camera.R;
import com.umeox.watch.moto.camera.bean.FilterView;

import java.util.List;

/**
 * Created by zl on 2018/7/2.
 */

public class FilterViewAdapter extends RecyclerView.Adapter<FilterViewAdapter.ItemViewHolder> {

    private List<FilterView> mPhotos;

    private FilterView mPhotosSelected = null;

    private ItemClickListener itemClickListener;


    public FilterViewAdapter(List<FilterView> photos, ItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
        this.mPhotos = photos;
    }

    @NonNull
    @Override
    public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_filter_view_list, parent, false);
        return new ItemViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {

        final FilterView photo = mPhotos.get(position);
        holder.iv.setImageResource(photo.getResId());
        holder.mView.setEnabled(photo.isSelected());
        holder.itemView.setOnClickListener(v -> itemClickListener.onItemClicked(position));
    }

    @Override
    public int getItemCount() {
        return mPhotos.size();
    }

    public void addOrRemoveSelected(int position) {
        if(position == indexOf()){
            resetData();
            notifyDataSetChanged();
            return;
        }
        resetData();
        final FilterView photo = mPhotos.get(position);
        mPhotosSelected = photo;
        photo.setSelected(true);
        notifyDataSetChanged();
    }


    public void resetData() {
        for (FilterView photo : mPhotos) {
            photo.setSelected(false);
        }
        mPhotosSelected = null;
    }

    class ItemViewHolder extends RecyclerView.ViewHolder {
        private ImageView iv;
        private ImageView mView;

        public ItemViewHolder(View itemView) {
            super(itemView);
            iv = itemView.findViewById(R.id.imageView);
            mView = itemView.findViewById(R.id.iv_selected);
        }
    }

    public interface ItemClickListener {
        void onItemClicked(int position);
    }


    public FilterView getPhotosSelected() {
        return mPhotosSelected;
    }

    public boolean isNoItemSelected() {
        return getPhotosSelected() == null;
    }

    public int indexOf() {
        if(getPhotosSelected() == null){
            return  -1;
        }
        return mPhotos.indexOf(getPhotosSelected());
    }

}

